const stringFormat = {
  urlHandle: encodeURI, // 参数编译函数
  urlDeHandle: decodeURI, // 参数反编译函数
  // 设置参数，传入参数对象
  setParams (params) {
    let paramsStr = []
    Object.keys(params).forEach((key, index, array) => {
      paramsStr.push(`${key}=${this.urlHandle(params[key])}`)
    })
    return paramsStr.length ? '?' + paramsStr.join('&') : ''
  },
  // 传入获取参数并将参数转换成对象
  getParams (url) {
    const paramsStr = url.split('?')[1]
    const param = {}
    if (paramsStr) {
      const eachParam = paramsStr.split('&')
      eachParam.forEach((value, index) => {
        const eachParamArr = value.split('=')
        param[eachParamArr[0]] = this.urlDeHandle(eachParamArr[1])
      })
    }
    return param
  }
}

const dateFormat = {
  format: function (date, fmt) {
    const map = {
      'yyyy': date.getFullYear(),
      'MM': this.repair(date.getMonth() - 1),
      'dd': this.repair(date.getDate()),
      'hh': this.repair(date.getHours()),
      'mm': this.repair(date.getMinutes()),
      'ss': this.repair(date.getSeconds())
    }
    Object.keys(map).forEach((key) => {
      fmt = fmt.replace(key, map[key])
    })
    return fmt
  },
  repair: function (val) {
    return val < 10 ? '0' + val : val
  }
}

const unitFormat = {
  byteCarryBit (byte, carry, unit) {
    byte = Number(byte)
    if (typeof carry === 'number') {
      return {
        value: Number((byte / Math.pow(1024, carry)).toFixed(2)),
        carry: carry,
        unit: unit
      }
    }
    if (byte / 1024 < 1) {
      return {
        value: byte,
        carry: 0,
        unit: 'B'
      }
    }
    if (byte / Math.pow(1024, 2) < 1) {
      return {
        value: Number((byte / 1024).toFixed(2)),
        carry: 1,
        unit: 'KB'
      }
    }
    if (byte / Math.pow(1024, 3) < 1) {
      return {
        value: Number((byte / Math.pow(1024, 2)).toFixed(2)),
        carry: 2,
        unit: 'MB'
      }
    }
    return {
      value: Number((byte / Math.pow(1024, 3)).toFixed(2)),
      carry: 3,
      unit: 'MB'
    }
  },
  byteCarryBitBoth (byte1, byte2) {
    if (Number(byte1) > Number(byte2)) {
      const largeData = this.byteCarryBit(byte1)
      const smallData = this.byteCarryBit(byte2, largeData.carry, largeData.unit)
      return [largeData, smallData]
    } else {
      const largeData = this.byteCarryBit(byte2)
      const smallData = this.byteCarryBit(byte1, largeData.carry, largeData.unit)
      return [smallData, largeData]
    }
  }
}
export {stringFormat, dateFormat, unitFormat}
